package com.z.redis;

import com.z.redis.command.Command;
import com.z.redis.util.TRACEID;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.apache.log4j.Logger;

/**
 * Redis 服务端的核心命令处理器，负责接收、执行命令并返回响应
 */
public class CommandHandler extends SimpleChannelInboundHandler<Command> {
    private static final Logger LOGGER = Logger.getLogger(CommandHandler.class);
    private final RedisCore redisCore; // 执行具体Redis命令

    public CommandHandler(RedisCore redisCore){
        this.redisCore = redisCore;
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, Command command) throws Exception {
        String traceId = TRACEID.currentTraceId(); // 获得当前请求的追踪ID
        LOGGER.debug("traceId:"+ traceId+" 本次处理的命令："+command.type().name());
        try {
            command.handle(ctx, redisCore); // 执行Redis命令
        } catch (Exception e) {
            LOGGER.error("traceId:"+ traceId+" 处理命令出错："+command.type().name(), e);
        }
        LOGGER.debug("traceId: "+traceId+" 命令处理完毕");
    }

    /**
     * 异常处理
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        LOGGER.error("处理命令出错", cause);
    }

    /**
     * 连接关闭
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception{
        super.channelUnregistered(ctx);;
        ctx.close(); // 关闭连接
    }

    /**
     * 数据刷新
     * @param ctx
     * @throws Exception
     */
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception{
//        super.channelUnregistered(ctx);
        super.channelReadComplete(ctx);
        ctx.flush(); // 刷新缓冲区 立即发送请求
    }
}
